package youleche.com.controler.servlet;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;

import youleche.com.business.BShare;
import youleche.com.business.BVehicleImageInfo;
import youleche.com.common.IDFactory;
import youleche.com.controler.servlet.common.UlecheHttpServlet;
import youleche.com.factory.MLLogFactory;
import youleche.com.interfaces.LoginAction;
import youleche.com.model.MShare;
import youleche.com.model.MVehicleImageInfo;
import youleche.com.util.DateUtil;
import youleche.com.util.EditorUtil;
import youleche.com.util.FileUtil;
import youleche.com.util.JsonHelper;
import youleche.com.util.StaticUtil;

/**
 * Servlet implementation class SShareServlet
 */
public class SShareServlet extends UlecheHttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * freemark静态化配置类
	 */
	 private Configuration cfg = null;
	 
	 @Override
     public void init() throws ServletException
     {
        cfg = new Configuration();
        cfg.setServletContextForTemplateLoading(this.getServletContext(), null);
     }
	 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SShareServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		int action = Integer.parseInt(request.getParameter("action"));
		switch(action){
			case 0:
				//添加分享攻略
				this.addShare(request, response);
				break;
			case 1: 
				//获取分享功能列表信息
				break;
		}
	}
	
	
	
	/**
	 * 添加分享攻略
	 * @param request
	 * @param response
	 */
	private void addShare(HttpServletRequest request, HttpServletResponse response){
		try {
			LoginAction loginHandler = new LoginAction();
			if(!loginHandler.is_Login(request, response)){ //未登录，请登录
				super.response(response, "2");
				return;
			}
			
			MShare share = (MShare)JsonHelper.getObjectByJsonStringAndGson(request, MShare.class);
			share.setId(IDFactory.getId("mlc", "share"));
			String userName = loginHandler.getLoginName(request, response);
			if("".equals(userName)){ //用户名为空，请登录
				super.response(response, "2");
				return;
			}
			
			share.setUserName(userName);
			share.setCount("0");
			share.setAddTime(DateUtil.getNowDate());
			List<String> imgList = EditorUtil.getImagePathListByContent(share.getContent());
			for (String imgPath : imgList) {
				share.setContent(share.getContent().replace("uploadTemp/" + imgPath, "upload/" + imgPath));
			}
			
			BShare handler = new BShare();
			if(handler.addShare(share) > 0){
				this.handleImageByContent(imgList);
				this.batchAddImage(imgList, share);
				StaticUtil.staticShare(share, cfg, request, response);	
				StaticUtil.staticQyPlaying(cfg, request, response);
				super.response(response, share.getId()); //添加成功
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			MLLogFactory.exceptionLog("添加骑游趣事出错", "添加骑游趣事出错", e.getMessage(), request.getRemoteAddr());
			super.response(response, "0");
		}
		
		super.response(response, "0");
	}
	
	/**
	 * 批量添加图片进入图片库
	 * @param imgPathList 图片列表
	 * @param share 分享信息
	 */
	private void batchAddImage(List<String> imgPathList, MShare share){
		BVehicleImageInfo imageHandler = new BVehicleImageInfo();
		MVehicleImageInfo imageInfo = null;
		for (String path : imgPathList) {
			imageInfo = new MVehicleImageInfo();
			imageInfo.setImagePath(path);
			imageInfo.setImageType("5"); //5代表分享骑游攻略
			imageInfo.setSellerId(share.getUserName());
			imageInfo.setVehicleId(share.getId());
			imageInfo.setAddTime(DateUtil.getNowDate());
			imageInfo.setImageId(IDFactory.getId("mlc", "sharefeel"));
			try {
				imageHandler.addVehicleImageInfo(imageInfo);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
	}
	/**
	 * 根据内容处理图片信息
	 * @param imgPathList 图片id以及路径
	 */
	private void handleImageByContent(List<String> imgPathList){
		//批量复制图片到正式库
		//批量删除临时库图片
		String tempDir = this.getServletConfig().getServletContext().getRealPath("") + "/uploadTemp/"; //临时库
		String normalDir = this.getServletConfig().getServletContext().getRealPath("") + "/upload/"; //正式库
		for (String path : imgPathList) {
			FileUtil.copyFile(tempDir + path, normalDir + path);
			FileUtil.deleteFile(path, tempDir);
		}
	}
}
